import { BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { useEffect, useRef } from 'react';

import { LineChartDataItem } from '@/types/know/know';

import type { EChartsType, EChartsCoreOption } from 'echarts';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  CanvasRenderer,
]);

interface UserDislikeChartProps {
  data: LineChartDataItem[];
  title?: string;
  height?: number;
}

const UserDislikeChart = ({ data, title, height = 200 }: UserDislikeChartProps) => {
  const chartRef = useRef<HTMLDivElement | null>(null);
  const chartInstance = useRef<EChartsType | null>(null);

  useEffect(
    function setupChart() {
      if (!chartRef.current || !data?.length) return;

      // 初始化图表
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }
      chartInstance.current = echarts.init(chartRef.current) as unknown as EChartsType;

      const xData = data.map(({ _id: id }) => id);
      const solvedData = data.map((item: any) => item.total_solved ?? 0);
      const unsolvedData = data.map((item: any) => item.total_unsolved ?? 0);
      const totalData = data.map(
        (item: any, idx: number) =>
          (item.feedbackCount ?? solvedData[idx] + unsolvedData[idx]) || 0,
      );

      const maxVal = Math.max(...totalData, 0);
      const yAxisMax = maxVal > 0 ? Math.ceil(maxVal * 1) + 1 : 1;

      const option: EChartsCoreOption = {
        title: {
          text: title,
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          appendToBody: true,
          confine: false,
          backgroundColor: 'rgba(255, 255, 255, 0.6)',
          borderColor: 'rgba(255, 255, 255, 0.6)',
          borderWidth: 1,
          borderRadius: 8,
          textStyle: { color: '#333' },
          extraCssText:
            'z-index:9999; backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(10px); box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);',
          formatter: (params: any) => {
            const dataIndex = params?.[0]?.dataIndex ?? 0;
            const current: any = data[dataIndex] || {
              feedbackCount: 0,
              total_solved: 0,
              total_unsolved: 0,
            };
            const total =
              current.feedbackCount ?? solvedData[dataIndex] + unsolvedData[dataIndex] ?? 0;
            const solved = solvedData[dataIndex] ?? 0;
            const unsolved = unsolvedData[dataIndex] ?? 0;
            const time = xData[dataIndex];
            // const weekdayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            // const dayLabel = dayjs(xData[dataIndex]).isValid()
            //   ? weekdayMap[dayjs(xData[dataIndex]).day()]
            //   : xData[dataIndex] || '';

            return `
            <div style="padding:12px 14px;width:220px;">
              <div style="display:flex;justify-content:space-between;align-items:center;color:#20242A;font-weight:600;">
                <span>用户点踩问题总数</span>
                <span>${total.toLocaleString()}</span>
              </div>
              <div style="color:#87919B;margin-top:4px;border-bottom:1px solid #F2F3F3;padding-bottom:10px;">${time}</div>

              <div style="display:flex;justify-content:space-between;align-items:center;margin-top:12px;">
                <div style="display:flex;align-items:center;color:#20242A;">
                  <span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:#5DD4FD;margin-right:8px;"></span>
                  <span>已处理</span>
                </div>
                <b>${solved.toLocaleString()}</b>
              </div>

              <div style="display:flex;justify-content:space-between;align-items:center;margin-top:8px;">
                <div style="display:flex;align-items:center;color:#20242A;">
                  <span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:#1E6FFA;margin-right:8px;"></span>
                  <span>未处理</span>
                </div>
                <b>${unsolved.toLocaleString()}</b>
              </div>
            </div>
          `;
          },
        },
        legend: {
          top: 0,
          left: 15,
          icon: 'roundRect',
          itemWidth: 14,
          itemHeight: 14,
          itemGap: 15,
          itemStyle: { borderRadius: 16 },
          data: ['已处理', '未处理'],
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '0%',
          top: 40,
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLine: {
            lineStyle: { color: '#ccc' },
          },
          axisLabel: {
            color: '#87919D',
            formatter: (value: string) => {
              // 格式化日期显示为 MM-DD
              const date = new Date(value);
              return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date
                .getDate()
                .toString()
                .padStart(2, '0')}`;
            },
          },
        },
        yAxis: {
          type: 'value',
          nameTextStyle: { color: '#666', fontSize: 12 },
          axisLine: { show: false, lineStyle: { color: '#ccc' } },
          splitLine: { lineStyle: { color: '#f0f0f0', type: 'dashed' } },
          axisLabel: { color: '#87919D', fontSize: 12 },
          max: yAxisMax,
        },
        series: [
          {
            name: '未处理',
            type: 'bar',
            data: unsolvedData,
            itemStyle: {
              color: '#1E6FFA',
              borderRadius: [8, 8, 0, 0],
              emphasis: { color: '#1E6FFA' },
            },
            barWidth: (() => {
              if (xData.length === 7) return '20%';
              if (xData.length > 15) return '60%';
              return '8%';
            })(),
          },
          {
            name: '已处理',
            type: 'bar',
            barGap: '-100%',
            data: solvedData,
            itemStyle: {
              color: '#5DD4FD',
              borderRadius: [8, 8, 0, 0],
              emphasis: { color: '#5DD4FD' },
            },
            barWidth: (() => {
              if (xData.length === 7) return '20%';
              if (xData.length > 15) return '60%';
              return '8%';
            })(),
          },
        ],
        animation: true,
        animationDuration: 1200,
        animationEasing: 'cubicOut',
      };

      chartInstance.current.setOption(option, true);

      const handleResize = () => chartInstance.current && chartInstance.current.resize();
      window.addEventListener('resize', handleResize);

      return function cleanup() {
        window.removeEventListener('resize', handleResize);
        chartInstance.current && chartInstance.current.dispose();
      };
    },
    [data, title],
  );

  return (
    <div
      ref={chartRef}
      style={{
        width: '100%',
        height: `${height}px`,
        backgroundColor: '#fff',
        borderRadius: '10px',
      }}
    />
  );
};

export default UserDislikeChart;
